# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/10/13 6:01 下午
# @Author  : 白辉东
# @Mail    : masterbai2018@outlook.com
# @File    : serializers.py
# @Software: PyCharm
from rest_framework import serializers, status
from rest_framework.response import Response
from rest_framework.serializers import ModelSerializer
from .models import TestCase, SpeakerProduct, CaseModule, SpeakerParams
from task.models import TaskModel
from django.core.exceptions import ObjectDoesNotExist


class TestCaseModelSerializer(ModelSerializer):
    class Meta:
        model = TestCase
        fields = "__all__"


# 用例模块序列化器
class CaseModuleModelSerializer(ModelSerializer):
    # 获取当前模块下的所有用例
    # testcases = TestCaseModelSerializer(read_only=True, many=True)

    class Meta:
        model = CaseModule
        fields = ['id', 'module_name']


# 仅仅序列化模块
class ModuleModelSerializer(ModelSerializer):
    class Meta:
        model = CaseModule
        fields = ['id', 'module_name']


# 音箱产品序列化器
class SpeakerProductModelSerializer(ModelSerializer):
    # 查询产品下面的所有用例模块，注意这里的speaker一定要和CaseModule的外键的别名保持一致
    modules = ModuleModelSerializer(read_only=True, many=True)

    class Meta:
        model = SpeakerProduct
        fields = ['id', 'speaker_name', 'modules']


class SpeakerParamsSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpeakerParams
        fields = "__all__"


# 音箱任务信息序列化器
class SpeakerTaskInfoSerializer(ModelSerializer):
    # 现定义一个方法属性的序列化字段
    case_count = serializers.SerializerMethodField()

    # 获取任务列表数
    task_count = serializers.SerializerMethodField()

    params = SpeakerParamsSerializer()

    class Meta:
        model = SpeakerProduct
        fields = ['id', 'speaker_name', 'rom_version', 'params', 'system_version', 'case_count', 'task_count']

    # 自定义返回字段
    def get_case_count(self, obj):
        case_count = TestCase.objects.filter(module__speaker=obj.id).count()
        return case_count

    # 自定义返回字段
    def get_task_count(self, obj):
        task_count = TaskModel.objects.filter(task_type=obj.id).count()
        return task_count


class SpeakerAddSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpeakerProduct
        fields = ['speaker_name', 'rom_version', 'system_version']


class CaseModuleSerializer(serializers.ModelSerializer):
    class Meta:
        model = CaseModule
        fields = ['module_name']
